<?php

namespace summer\swoole\pool\simple\pool;

use summer\swoole\pool\Connection as AbstractConnection;
use summer\swoole\pool\Pool;

class Connection extends AbstractConnection
{
    /**
     * @var callable
     */
    public $callback;

    public $connection;

    public function __construct(Pool $pool, callable $callback)
    {
        $this->callback = $callback;
        parent::__construct($pool);
    }

    public function getActiveConnection()
    {
        if (! $this->connection || ! $this->check()) {
            $this->reconnect();
        }

        return $this->connection;
    }

    public function reconnect(): bool
    {
        $this->connection = ($this->callback)();
        $this->lastUseTime = microtime(true);
        return true;
    }

    public function close(): bool
    {
        $this->connection = null;
        return true;
    }
}